package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.IDCardUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInConfigDto;
import com.zzyl.nursing.dto.CheckInContractDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Arrays;

/**
 * 入住Service业务层处理
 *
 * @author zzyl
 * @date 2025-10-16
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    @Autowired
    private ContractMapper contractMapper;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 入住申请
     *
     * @param dto
     */
    @Override
    public void apply(CheckInApplyDto dto) {
        // 判断老人是否已经入住
        // 通过身份证号查询老人
        Elder elder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo())
                .eq(Elder::getStatus, 1));
        if (ObjectUtils.isNotEmpty(elder)) {
            throw new RuntimeException("该老人已经入住");
        }
        //走到这里证明老人没有数据也没有入住
        // 1更新床位的状态  已入住，从前端获取床号。流程为：先取出数据，在进行封装，在存储
        Bed bed = bedMapper.selectBedById(dto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);
        // 2新增或更新老人
        elder = saveorupdate(dto, bed);

        // 3新增签约办理
        insertContract(dto, elder);
        // 4新增入住信息
        Long checkInId = saveCheckIn(dto, elder);
        // 5新增入住配置信息
        insertCheckInConfig(dto, checkInId);
    }

    /**
     * 新增入住配置信息
     * @param dto
     */
    private void insertCheckInConfig(CheckInApplyDto dto, Long checkInId) {
        CheckInConfigDto checkInConfigDto = dto.getCheckInConfigDto();
        CheckInConfig checkInConfig = BeanUtil.toBean(checkInConfigDto, CheckInConfig.class);
        checkInConfig.setCheckInId(checkInId);
        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     * 新增入住信息
     * @param dto
     */
    private Long saveCheckIn(CheckInApplyDto dto, Elder elder) {
        CheckInConfigDto checkInConfigDto = dto.getCheckInConfigDto();
        CheckIn checkin = BeanUtil.toBean(checkInConfigDto, CheckIn.class);
        checkin.setElderId(elder.getId());
        checkin.setElderName(elder.getName());
        checkin.setIdCardNo(elder.getIdCardNo());

        checkin.setBedNumber(elder.getBedNumber());
        checkin.setRemark(JSON.toJSONString(dto.getElderFamilyDtoList()));
        checkin.setStatus(0);
        checkInMapper.insert(checkin);

        return checkin.getId();
    }

    /**
     * 新增合同
     * @param dto
     */
    private void insertContract(CheckInApplyDto dto, Elder elder) {
        CheckInContractDto checkInContractDto = dto.getCheckInContractDto();
        Contract contract = BeanUtil.toBean(checkInContractDto, Contract.class);
        contract.setContractNumber(CodeGenerator.generateContractNumber());
        contract.setElderId(Integer.parseInt(elder.getId() + ""));
        contract.setElderName(elder.getName());
        // 状态、开始时间、结束时间
        // 签约时间小于等于当前时间，合同生效中
        LocalDateTime checkInStartTime = dto.getCheckInConfigDto().getStartDate();
        LocalDateTime checkInEndTime = dto.getCheckInConfigDto().getEndDate();
        Integer status = checkInStartTime.isBefore(LocalDateTime.now()) ? 1 : 0;
        contract.setStatus(status);
        contract.setStartDate(checkInStartTime);
        contract.setEndDate(checkInEndTime);

        contractMapper.insert(contract);
    }

    /**
     * 新增或更新老人信息
     * @param dto
     */
    private Elder saveorupdate(CheckInApplyDto dto, Bed bed) {
        CheckInElderDto checkInElderDto = dto.getCheckInElderDto();
        //数据拷贝
        Elder newelder = BeanUtil.toBean(checkInElderDto, Elder.class);
        newelder.setBedNumber(bed.getBedNumber());
        newelder.setBedId(bed.getId());
        newelder.setStatus(1);
        //根据身份证查询老人，并且状态不等于1，不为空则表示更新，为空则新增
        Elder oldelder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo())
                .ne(Elder::getStatus, 1)
        );
        if (ObjectUtils.isNotEmpty(oldelder)) {
            // 更新
            elderMapper.updateElder(newelder);
        } else {
            //新增
            elderMapper.insert(newelder);
        }
        return newelder;
    }

    /**
     * 查询入住详情
     *
     * @param id
     * @return
     */
   @Override
public CheckInDetailVo detail(Long id) {
    //封装数据
    CheckInDetailVo vo = new CheckInDetailVo();

    // 使用 getById 方法查询入住信息
    CheckIn checkIn = getById(id);
    if (checkIn != null) {
        //checkineldervo - 根据入住信息中的elderId查询老人信息
        Elder elder = elderMapper.selectById(checkIn.getElderId());
        if (elder != null) {
            CheckInElderVo checkInElderVo = BeanUtil.toBean(elder, CheckInElderVo.class);
            if (elder.getIdCardNo() != null) {
                checkInElderVo.setAge(IDCardUtils.getAgeByIdCard(elder.getIdCardNo()));
            }
            vo.setCheckInElderVo(checkInElderVo);
        }

        //elderfamilyvo - 解析入住信息中的备注字段（存储的是家属信息）
        if (checkIn.getRemark() != null) {
            try {
                List<ElderFamilyVo> familyList = JSON.parseArray(checkIn.getRemark(), ElderFamilyVo.class);
                vo.setElderFamilyVoList(familyList);
            } catch (Exception e) {
                // 解析失败则忽略
            }
        }

        //checkinconfigvo - 根据入住ID查询配置信息
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(Wrappers.<CheckInConfig>lambdaQuery()
                .eq(CheckInConfig::getCheckInId, id));
        if (checkInConfig != null) {
            CheckInConfigVo checkInConfigVo = BeanUtil.toBean(checkInConfig, CheckInConfigVo.class);
            checkInConfigVo.setBedNumber(elder.getBedNumber());
            checkInConfigVo.setStartDate(checkIn.getStartDate());
            checkInConfigVo.setEndDate(checkIn.getEndDate());
            vo.setCheckInConfigVo(checkInConfigVo);
        }
    }

    //contract - 根据入住ID查询合同信息
    Contract contract = contractMapper.selectOne(Wrappers.<Contract>lambdaQuery()
            .eq(Contract::getElderId, checkIn != null ? checkIn.getElderId() : null));
    if (contract != null) {
        vo.setContract(contract);
    }

    return vo;
}

}
